<template>
  <div class="search-container">
    <form action="/">
      <van-search v-model="searchText" show-action placeholder="请输入搜索关键词" @search="onSearch(searchText)" @cancel="onCancel" @focus="focus" />
    </form>
    <SearchResult v-if="isResultShow" :search-text="searchText" />
    <SearchSuggestion v-else-if="searchText" :search-text="searchText" @search="onSearch" />
    <SearchHistory v-else :searchHistories="searchHistories" @search="onSearch" @updat-histories="searchHistories = $event" />
  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchResult from './components/search-result'
import SearchSuggestion from './components/search-suggestion'
import { setItem, getItem } from '@/utils/storage'
// import { getSearchHistories } from '@/api/search'
import { mapState } from 'vuex'
export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggestion
  },
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: getItem('search-histories') || []
    }
  },
  computed: {
    ...mapState(['user'])
  },
  watch: {
    searchHistories () {
      setItem('search-histories', this.searchHistories)
    }
  },
  created () {
    console.log(this.searchHistories)
    this.loadSearchHistories()
  },
  mounted () { },
  methods: {
    focus () {
      console.log('bianhua1')
      this.isResultShow = false
    },
    onSearch (searchText) {
      this.searchText = searchText

      const index = this.searchHistories.indexOf(searchText)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(searchText)
      // console.log(this.searchHistories)
      // setItem("search-histories", this.searchHistories);

      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    },
    async loadSearchHistories () {
      const searchHistories = getItem('search-histories') || []
      // if (this.user) {
      //   const { data } = await getSearchHistories();
      //   searchHistories = [...new Set([
      //     ...searchHistories,
      //     ...data.data.keywords
      //     ])]

      // }
      this.searchHistories = searchHistories
    }
  }
}
</script>
<style scoped lang="less">
</style>
